#!/bin/bash

# 
# Pulling kernel image and deviceteee file from server.
# 
# Example usage:
# kernel_update.sh ["./zedboard"]
# 
# Introduce:
# parameter is a path to store files that are pulled from server.
# 
version=V1.0
echo "The script is $version."
server="http://192.168.50.4:8001/arf9022/release/"

if ! [ -x "$(command -v wget)" ]; then
	echo 'Error: wget is not installed.' >&2
	exit 1
fi

drvVer=0
board=${1:-"./zedboard"}
echo "board is "$board

function get_newest_ver()
{
	if [ ! -n $1 ];then
		return 1
	fi
	local url=$1

	local verfile=$(basename $0)
	verfile=${verfile%.*}
	wget -q "${url}" -O ".${verfile}_info.txt"
	local newest_ver=0
	while read line
	do
		if [[ $line =~ "href=\"V" ]]
		then
			tmp=${line%%'/'*}
			tmp=${tmp#*'V'}
			if [ $(expr $tmp \> $newest_ver) -eq 1 ];then
				newest_ver=$tmp
			fi
		fi
	done < ".${verfile}_info.txt"
	rm .${verfile}_info.txt
	echo "$newest_ver"
	return 
}

if [ ! -d $board ];then
    mkdir $board
fi

new=$(get_newest_ver $server)

if [ -f "$board/ver" ];then

	drvVer=$(crudini --get "$board/ver" Driver ver)
	if [[ ! -n $drvVer ]];then
		crudini --set "$board/ver" Driver ver 0
		drvVer=0
	fi
else 
	touch "$board/ver"
	crudini --set "$board/ver" Driver ver 0
fi

echo "drvVer is $drvVer"

if [ $(expr $new \> $drvVer) -eq 1 ];then
	echo "Update boot files"
	if [ -f "$board/uImage" ];then
		rm $board/uImage
	fi
	if [ -f "$board/devicetree.dtb" ];then
		rm $board/devicetree.dtb
	fi
	wget -c "${server}V$new/uImage" -O $board/uImage
	wget -c "${server}V$new/devicetree.dtb" -O $board/devicetree.dtb
	rm "$board"/dts/* 
	if [[ $board =~ "zedboard" ]];then
		wget -c "${server}V$new/dts/zynq-zed.dtsi" -P $board/dts/
		wget -c "${server}V$new/dts/zynq-zed-adv7511.dtsi" -P $board/dts/
		wget -c "${server}V$new/dts/zedboard.dts" -P $board/dts/
	else 
		wget -c "${server}V$new/dts/zynq-ZC706.dtsi" -P $board/dts/
		wget -c "${server}V$new/dts/zynq-zc706-adv7511.dtsi" -P $board/dts/
		wget -c "${server}V$new/dts/avc.dts" -P $board/dts/
	fi
	wget -c "${server}V$new/dts/avc-evb.dtsi" -P $board/dts/
	wget -c "${server}V$new/dts/zynq.dtsi" -P $board/dts/
	wget -c "${server}V$new/dts/zynq-7000.dtsi" -P $board/dts/

	echo "Update boot files over."
	crudini --set "$board/ver" Driver ver $new
	exit 0
fi

echo "Boot files is the newest, not need to update."
